// 网关配置的前缀
var companyServer = "/companySer"

let type = "POST"

// let companyId = "1354255569179971586";
let companyId = "";

let Authorization = "";
let refreshToken = "";

// 加载页面时读取后台的 ip
window.onload = function () {
    let accountStatus = $("#accountStatus").html();
    if(accountStatus !== "正常"){
        $("#forbidden").removeAttr("hidden");
    }

    let authorities = $("#authorities").html();
    unauthorized_2(authorities, "companyInfo");

    $.ajaxSettings.async = false;
    $.getJSON("/js/properties.json", function (data) {
        companyServer = data.companyServer;
    });
    // 获取令牌
    Authorization = getCookie("Authorization")
    refreshToken = getCookie("refreshToken")

    companyId = $("#companyId").html()
    $(".userId").val(companyId);
    getCompanyInfo()

    // $("#main-wrapper *").attr('readonly', true)
    //                     .attr('disabled', true)
    //                     .removeAttr('onclick');

    getFinancingSituation();// 获得 融资情况
    getCompanySize();// 获得 公司规模
    getEnterprisesType();// 获得 企业类型
    getOperationStatus();// 获得 经营状态

}

// 企业 Logo
$("#Logo").change(function (event) {
    // 获取图片元素
    var ele = event.target;

    if (!/.(gif|jpg|jpeg|png|GIF|JPG|bmp)$/.test(ele.value)) {
        alert("图片类型必须是.gif,jpeg,jpg,png,bmp中的一种");
        return false;
    }

    var files = ele.files;
    if (files && files.length <= 0) {
        alert("出错了，请重新上传。")
    }

    var file = files[0];
    if (file.size > 1024 * 100) {
        alert('照片大小不能超过 100KB!');
        return false;
    }

    // 获取目前上传的文件

    var path = URL.createObjectURL(file);
    $(".create-photo-left1").css("background-image", "url(" + path + ")")
        .css("background-repeat", "no-repeat")
        .css('background-size', '100% 100%');
    $("#photo-logo *").hide();

    // 将文件传到后端
    $('#uploadLogo').ajaxSubmit({
        datatype: 'json',
        success: function (res) {
            cocoMessage.info(2000, "图片上传成功", function () {
            });
        },
        error: function (res) {
            cocoMessage.error(2000, "图片上传出错，请重试", function () {
            });
        }
    });
});

// 企业图片
$("#companyPhoto").change(function (event) {
    // 获取图片元素
    var ele = event.target;

    if (!/.(gif|jpg|jpeg|png|GIF|JPG|bmp)$/.test(ele.value)) {
        alert("图片类型必须是.gif,jpeg,jpg,png,bmp中的一种");
        return false;
    }

    var files = ele.files;
    if (files && files.length <= 0) {
        alert("出错了，请重新上传。")
    }

    var file = files[0];
    if (file.size > 1024 * 100) {
        alert('照片大小不能超过 100KB!');
        return false;
    }

    // 获取目前上传的文件

    var path = URL.createObjectURL(file);
    $(".create-photo-left2").css("background-image", "url(" + path + ")")
        .css("background-repeat", "no-repeat")
        .css('background-size', '100% 100%');
    $("#photo-area *").hide();

    // 将文件传到后端
    $('#photo').ajaxSubmit({
        datatype: 'json',
        success: function (res) {
            cocoMessage.info(2000, "图片上传成功", function () {
            });
        },
        error: function (res) {
            cocoMessage.error(2000, "图片上传出错，请重试", function () {
            });
        }
    });
});

// 日期选择
$("#establishmentDate").datetimepicker({
    format: 'yyyy-mm-dd',
    language: 'zh-CN',
    todayBtn: true,
    startView: 4,
    maxView: 'decade',
    minView: 2,
    forceParse: false,
    bootcssVer: 3,
    autoclose: true //选择日期后自动关闭
});

// 获得 融资情况
function getFinancingSituation() {
    let $list = $("#financingSituation .list");
    let $mySelect = $("#financingSituation .mySelect");
    $.ajax({
        type: "get",
        async: false,
        url: companyServer + "/company/financingSituation",
        success: function (data) {
            console.log("融资情况");
            //清空数据
            $list.empty();

            // 如果为空
            if (data.datas.length <= 0) {
                $mySelect.empty();
                $mySelect.append(
                    "<option>暂无数据</option>"
                    // "<li data-value='' class='option' disabled='disabled'>暂无数据</li>"
                );
            }

            //返回的数据用data.rows获取内容
            $.each(data.datas, function (i, item) {
                $list.append(
                    "<li data-value='" + item.value + "' class='option'>" + item.value + "</li>"
                );
            });
        },
        error: function (err) {
            $mySelect.empty();
            $mySelect.append(
                "<option>暂无数据</option>"
            );
            console.log(err);
        }

    });
}

// 获得 公司规模
function getCompanySize() {
    let $list = $("#companySize .list");
    let $mySelect = $("#companySize .mySelect");
    $.ajax({
        type: "get",
        async: false,
        url: companyServer + "/company/companySize",
        success: function (data) {
            console.log("公司规模");

            //清空数据
            $list.empty();

            // 如果为空
            if (data.datas.length <= 0) {
                $mySelect.empty();
                $mySelect.append(
                    "<option>暂无数据</option>"
                );
            }

            //返回的数据用data.rows获取内容
            $.each(data.datas, function (i, item) {
                $list.append(
                    "<li data-value='" + item.value + "' class='option'>" + item.value + "</li>"
                );
            });
        },
        error: function (err) {
            $mySelect.empty();
            $mySelect.append(
                "<option>暂无数据</option>"
            );
            console.log(err);
        }
    });
}

// 获得 企业类型
function getEnterprisesType() {
    let $list = $("#enterprisesType .list");
    let $mySelect = $("#enterprisesType .mySelect");
    $.ajax({
        type: "get",
        async: false,
        url: companyServer + "/company/enterprisesType",
        success: function (data) {
            console.log("企业类型");

            //清空数据
            $list.empty();

            // 如果为空
            if (data.datas.length <= 0) {
                $mySelect.empty();
                $mySelect.append(
                    "<option>暂无数据</option>"
                );
            }

            //返回的数据用data.rows获取内容
            $.each(data.datas, function (i, item) {
                $list.append(
                    "<li data-value='" + item.value + "' class='option'>" + item.value + "</li>"
                );
            });
        },
        error: function (err) {
            $mySelect.empty();
            $mySelect.append(
                "<option>暂无数据</option>"
            );
            console.log(err);
        }
    });
}

// 获得 经营状态
function getOperationStatus() {
    let $mySelect = $("#operationStatus .mySelect");
    let $list = $("#operationStatus .list");
    $.ajax({
        type: "get",
        async: false,
        url: companyServer + "/company/operationStatus",
        success: function (data) {
            console.log("经营状态");

            //清空数据
            $list.empty();

            // 如果为空
            if (data.datas.length <= 0) {
                $mySelect.empty();
                $mySelect.append(
                    "<option>暂无数据</option>"
                );
            }

            //返回的数据用data.rows获取内容
            $.each(data.datas, function (i, item) {
                $list.append(
                    "<li data-value='" + item.value + "' class='option'>" + item.value + "</li>"
                );
            });
        },
        error: function (err) {
            $mySelect.empty();
            $mySelect.append(
                "<option>暂无数据</option>"
            );
            console.log(err);
        }
    });
}

$("#submit").click(function () {


    // let companyId = "1354255569179971586";
    let companyName = $("#companyName").val();
    let financingSituation = $('#financingSituation .current').html();
    let companySize = $('#companySize .current').html();
    let industry = $("#industry").val();
    let introduction = $("#introduction").val();
    let legalRepresentative = $("#legalRepresentative").val();
    let registeredCapital = $("#registeredCapital").val();
    let establishmentDate = $("#establishmentDate").val();
    let enterprisesType = $('#enterprisesType .current').html();
    let operationStatus = $('#operationStatus .current').html();
    let registeredAddress = $("#registeredAddress").val();
    let creditCode = $("#creditCode").val();
    let businessNature = $("#businessNature").val();
    let companyAddress = $("#companyAddress").val();

    if (companyName === "") {
        $("#error_companyName").html("不能为空");
        return;
    } else {
        $("#error_companyName").html();
    }

    if (financingSituation === "请选择 融资情况") {
        $("#error_financingSituation").html("不能为空");
        return;
    } else {
        $("#error_financingSituation").html();
    }

    if (companySize === "请选择 公司规模") {
        $("#error_companySize").html("不能为空");
        return;
    } else {
        $("#error_companySize").html();
    }

    if (industry === "") {
        $("#error_industry").html("不能为空");
        return;
    } else {
        $("#error_industry").html();
    }

    if (introduction === "") {
        $("#error_introduction").html("不能为空");
        return;
    } else {
        $("#error_introduction").html();
    }

    if (legalRepresentative === "") {
        $("#error_legalRepresentative").html("不能为空");
        return;
    } else {
        $("#error_legalRepresentative").html();
    }

    if (registeredCapital === "") {
        $("#error_registeredCapital").html("不能为空");
        return;
    } else {
        $("#error_registeredCapital").html();
    }

    if (establishmentDate === "") {
        $("#error_establishmentDate").html("不能为空");
        return;
    } else {
        $("#error_establishmentDate").html();
    }

    if (enterprisesType === "请选择 企业类型") {
        $("#error_enterprisesType").html("不能为空");
        return;
    } else {
        $("#error_enterprisesType").html();
    }

    if (operationStatus === "请选择 经营状态") {
        $("#error_operationStatus").html("不能为空");
        return;
    } else {
        $("#error_operationStatus").html();
    }

    if (registeredAddress === "") {
        $("#error_registeredAddress").html("不能为空");
        return;
    } else {
        $("#error_registeredAddress").html();
    }

    if (creditCode === "") {
        $("#error_creditCode").html("不能为空");
        return;
    } else {
        $("#error_creditCode").html();
    }

    if (businessNature === "") {
        $("#error_businessNature").html("不能为空");
        return;
    } else {
        $("#error_businessNature").html();
    }

    if (companyAddress === "") {
        $("#error_companyAddress").html("不能为空");
        return;
    } else {
        $("#error_companyAddress").html();
    }

    $.ajax({
        type: "POST",
        async: false,
        url: companyServer + "/company/companyInfo",
        headers: {
            "Content-Type": "application/json",
            "Authorization": Authorization,
            "refreshToken": refreshToken,
        },
        data: JSON.stringify({
            "companyId": companyId,
            "companyName": companyName,
            "financingSituation": financingSituation,
            "companySize": companySize,
            "industry": industry,
            "introduction": introduction,
            "legalRepresentative": legalRepresentative,
            "registeredCapital": registeredCapital,
            "establishmentDate": establishmentDate,
            "enterprisesType": enterprisesType,
            "operationStatus": operationStatus,
            "registeredAddress": registeredAddress,
            "creditCode": creditCode,
            "businessNature": businessNature,
            "companyAddress": companyAddress,
        }),
        success: function (data) {
            if (data.resp_code === 0) {
                // 成功
                cocoMessage.info(2000, data.resp_msg, function () {
                });
                // location.reload();
            } else {
                // 失败
                cocoMessage.error(2000, data.resp_msg, function () {
                    console.log(data.resp_msg);
                });
            }
        },
        error: function (err) {
            // 异常
            cocoMessage.error(2000, err.statusText, function () {
                console.log(err);
            });
        }
    })
})

function getCompanyInfo(){
    $.ajax({
        type: "GET",
        async: false,
        url: companyServer + "/company/selectOneCompany?companyId="+companyId,
        headers: {
            "Content-Type": "application/json",
            "Authorization": Authorization,
            "refreshToken": refreshToken,
        },
        success: function (data) {
            let $systemInfo = $(".systemInfo");
            if (data.resp_code === 0) {
                // 成功
                let company = data.datas;

                // 设置部分字段不能修改
                $(".canNotUpdate").attr("readOnly", "true");
                $(".canNotUpdate").css("background", "#e7e7e7");

                $("#establishmentDate").datetimepicker("remove");

                let pathLogo = company.logo;
                let pathPhoto = company.companyPhoto;

                if (pathLogo === "" || pathLogo === null){

                }else {
                    $(".create-photo-left1").css("background-image", "url(" + pathLogo + ")")
                        .css("background-repeat", "no-repeat")
                        .css('background-size', '100% 100%');
                    $("#photo-logo *").hide();
                }

                if (pathPhoto === "" || pathPhoto === null){
                }else {
                    $(".create-photo-left2").css("background-image", "url(" + pathPhoto + ")")
                        .css("background-repeat", "no-repeat")
                        .css('background-size', '100% 100%');
                    $("#photo-area *").hide();
                }


                $("#companyId").val(company.companyId);
                $("#companyName").val(company.companyName);
                $("#industry").val(company.industry);
                $("#introduction").val(company.introduction);
                $("#legalRepresentative").val(company.legalRepresentative);
                $("#registeredCapital").val(company.registeredCapital);
                $("#establishmentDate").val(company.establishmentDate);
                $("#registeredAddress").val(company.registeredAddress);
                $("#creditCode").val(company.creditCode);
                $("#businessNature").val(company.businessNature);
                $("#companyAddress").val(company.companyAddress);

                $("#financingSituation .current").html(company.financingSituation);
                $("#companySize .current").html(company.companySize);
                $("#enterprisesType .current").html(company.enterprisesType);
                $("#operationStatus .current").html(company.operationStatus);

                $("#memberLevel").val(company.memberLevel);
                if (company.memberLevel === "免费版"){
                    $("#memberEndTime").val(" --- ")
                }else{
                    $("#memberEndTime").val(company.memberEndDate);
                }
                $("#hrNumber").val(company.hrNumber);
                $("#postNumber").val(company.postNumber);

            } else {
                // 失败
                $systemInfo.attr("hidden","true");
            }
        },
        error: function (err) {
            // 异常
            cocoMessage.error(2000, err.statusText, function () {
                console.log(err);
            });
        }
    })
}
